package com.dexilaonian.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.dexilaonian.R;
import com.dexilaonian.adpter.OrderDetailAdapter;
import com.dexilaonian.adpter.ShoppingCartAdapter;
import com.dexilaonian.bean.OrderDetailBean;
import com.dexilaonian.bean.PspecBean;
import com.dexilaonian.bean.PspecBean2;
import com.dexilaonian.bean.TrolleyBean;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.Student;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bakerj.backgrounddarkpopupwindow.BackgroundDarkPopupWindow;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ShoppingTrolleyActivity extends BaseActivity implements ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface {
    private static final int LDADDATA = 50;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service2)
    TextView baseTitleService2;
    @Bind(R.id.fenxiang_top)
    ImageView fenxiangTop;
    @Bind(R.id.tv_che_editor)
    TextView tvCheEditor;
    @Bind(R.id.trolley_recyclerview)
    ListView trolleyRecyclerview;
    @Bind(R.id.ck_all)
    CheckBox ckAll;
    @Bind(R.id.trolley_price)
    TextView trolleyPrice;
    @Bind(R.id.btn_trolley_order)
    Button btnTrolleyOrder;
    @Bind(R.id.lllll)
    LinearLayout lllll;
    private BackgroundDarkPopupWindow window;
    private List<TrolleyBean> shopList = new ArrayList<>();

    private List<String> trolley_list = new ArrayList<>();
    private List<Integer> list_delete = new ArrayList<>();
    private ShoppingCartAdapter shopadapter;
    private int totalCount;
    private double totalPrice;
    private boolean flag = true;
    private JSONArray jsonArray = new JSONArray();
    private String delete_reponse;
    private double mPosition = 1;
    private boolean FLAG = true;
    private ArrayList<PspecBean2> pspecBList = new ArrayList<>();
    ArrayList<Boolean> booleanList = new ArrayList<Boolean>();
    private PspecBean2 pspecBean;

    @Override
    public int getLayoutID() {
        return R.layout.activity_shopping_trolley;
    }

    @Override
    public void initView() {
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        pspecBList.clear();
        initShoppingTrolley();
        tvCheEditor.setVisibility(View.VISIBLE);
        baseTitleService2.setText("购物车");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.back, R.id.tv_che_editor, R.id.ck_all, R.id.btn_trolley_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_che_editor:
                flag = !flag;
                if (!flag) {
                    tvCheEditor.setText("完成");
                    trolleyPrice.setVisibility(View.GONE);
                    btnTrolleyOrder.setText("删除");
                    if (mPosition != 3) {
                        mPosition =2 ;
                    }
                    //shopadapter.isShow(false);
                } else {
                    tvCheEditor.setText("编辑");
                    trolleyPrice.setVisibility(View.VISIBLE);
                    btnTrolleyOrder.setText("下单");
                    //shopadapter.isShow(true);
                    mPosition =1 ;
                    initFinish();
                }
                break;
            case R.id.ck_all:
                if (shopList.size() == 0) {
                    showToast("没有商品哟！请添加商品");
                    mPosition = 10;
                    return;
                }
                FLAG = !FLAG;
                if (!FLAG) {
                    if (mPosition != 1) {
                        mPosition = 3;
                    }
                } else {
                    if (mPosition != 1) {
                        mPosition = 2;
                    }
                }
                if (shopList.size() != 0) {
                    if (ckAll.isChecked()) {
                        for (int i = 0; i < shopList.size(); i++) {
                            shopList.get(i).setChoosed(true);
                        }
                        shopadapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < shopList.size(); i++) {
                            shopList.get(i).setChoosed(false);
                        }
                        shopadapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            case R.id.btn_trolley_order:
                // 选中的需要提交的商品清单
                Log.e("点击后的position==",mPosition+"");
                 if (mPosition == 1) {
                     for (final TrolleyBean bean : shopList) {
                         boolean choosed = bean.isChoosed();
                         if (choosed) {
                             String shoppingName = bean.getProductName();
                             int count = bean.getQuantity();
                             int id = bean.getProduct_id();
                             pspecBean = new PspecBean2();
                             pspecBean.setQuantity(count);
                             pspecBean.setProductId(id);
                             pspecBean.setPspec(shoppingName);
                             pspecBList.add(pspecBean);
                         }
                     }
                     if (pspecBList.size() == 0) {
                         showToast("请选择商品");
                         return;
                     }
                     Intent intent = new Intent(ShoppingTrolleyActivity.this, ConfirmStoreActivity.class);
                     Bundle bundle = new Bundle();
                     bundle.putSerializable("PSPS",pspecBList);
                     intent.putExtras(bundle);
                     intent.putExtra("CONFIRMS", "CONFIRMS1");
                     startActivity(intent);
                  } else {
                      if (mPosition == 2) {
                          for (int i = 0; i < shopList.size(); i++) {
                              boolean isChoosed = shopList.get(i).isChoosed;
                              if (isChoosed) {
                               //怎样一次性删除选中的商品？？？？？？？？？？？？
                                  shopList.remove(i);
                            //      list_delete.add(i);
                                    i--;
                              //    booleanList.add(true);
                              } /*else {
                                  booleanList.add(false);
                              }
                              for (int j = 0; j < shopList.size(); j++) {
                                  if (booleanList.get(j)) {
                                      booleanList.remove(j);
                                      shopList.remove(j);
                                      j--;
                                      Log.e("TTTTTBoolean", "删除数据中:index:" + j + "当前集合大小:" + shopList.size());
                                  }
                              }*/
                          }
                           shopadapter.notifyDataSetChanged();
                          initFinish();
                      } else {
                          if (mPosition == 3) {
                              if (shopList != null) {
                                  AlertDialog alert = new AlertDialog.Builder(ShoppingTrolleyActivity.this).create();
                                  alert.setTitle("操作提示");
                                  alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                                  alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface dialog, int which) {
                                                  return;
                                              }
                                          });
                                  alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                                          new DialogInterface.OnClickListener() {
                                              @Override
                                              public void onClick(DialogInterface dialog, int which) {
                                                  //  modifyCountInterface.childDelete(position);//删除 目前只是从item中移除

                                                  shopList.clear();
                                                  initFinish();
                                                  shopadapter.notifyDataSetChanged();
                                              }
                                          });
                                  alert.show();
                                  return;
                              }
                          }
                      }
                  }
                break;
        }
    }

    private void initFinish() {
        //选中的需要提交的商品清单
        for (TrolleyBean bean:shopList){
            boolean choosed = bean.isChoosed();
            if (!choosed) {
                com.alibaba.fastjson.JSONObject jsonObject =new com.alibaba.fastjson.JSONObject();
                String shoppingName = bean.getProductName();
                int count = bean.getQuantity();
                int id = bean.getProduct_id();
                jsonObject.put("productId",id);
                jsonObject.put("quantity", count);
                jsonObject.put("pspec", shoppingName);


                jsonArray.add(jsonObject);
                Log.e("TTTTNAME22220", jsonArray+"====");
            }
        }
        final String finish_url = Constant.base_url + "/cart/edit_cart.do";
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e("TTTTNAME266666666", jsonArray.toJSONString());
                delete_reponse = Okhttp.sendPost(finish_url, jsonArray.toJSONString());
                Log.e("TTTTdelete123", delete_reponse);
                try {
                    JSONObject js = new JSONObject(delete_reponse);
                    String data = js.optString("data");
                    JSONObject jsonObject2 = new JSONObject(data);
                    Message message = myHandler.obtainMessage(LDADDATA);
                    message.obj = jsonObject2;
                    message.sendToTarget();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    public Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case LDADDATA:
                    // List<OrderDetailBean> confirmList = (List<OrderDetailBean>) msg.obj;
                    JSONObject jsonObject3 = (JSONObject) msg.obj;
                    Log.e("TTTjsonObject3", jsonObject3.toString());

                    String order_detail = jsonObject3.optString("order_detail");
                    String sale_order = jsonObject3.optString("sale_order");
                    try {
                        JSONObject sale_js = new JSONObject(sale_order);
                        Log.e("TTTsale_js", sale_js.toString());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    private void initShoppingTrolley() {
        showProgressBar(false);
        String shopping_url = Constant.base_url + "/cart/cart_list.do";
        Map<String, String> shopping_map = new HashMap<>();
        Okhttp.postString(true, shopping_url, shopping_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("TTTTLIST", response);
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        Intent intent = new Intent(ShoppingTrolleyActivity.this, LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    if (status == 0) {
                        shopList.clear();
                        String data = jsonObject.optString("data");
                        if (data == null) {
                            showToast("购物车空空的，请添加商品");
                            return;
                        }
                        JSONObject data_json = new JSONObject(data);
                        String items = data_json.optString("items");
                        ArrayList<TrolleyBean> trolleyBeen = JsonUtil.json2beans(items, TrolleyBean.class);
                        shopList.addAll(trolleyBeen);
                        shopadapter = new ShoppingCartAdapter(ShoppingTrolleyActivity.this);
                        shopadapter.setCheckInterface(ShoppingTrolleyActivity.this);
                        shopadapter.setModifyCountInterface(ShoppingTrolleyActivity.this);
                        trolleyRecyclerview.setAdapter(shopadapter);
                        shopadapter.setShoppingCartBeanList(shopList);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }

    /**
     * 显示popupWindow
     */
    private void doctor_poWindow() {

        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context
                .LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_type, null);
        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                1100);

        ImageView quxiao = (ImageView) view.findViewById(R.id.quxiao_type);
        Button btyType = (Button) view.findViewById(R.id.btn_type);

        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()

        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(ShoppingTrolleyActivity.this.findViewById(R.id.lllll),
                Gravity.BOTTOM, 0, 0);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });
        btyType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();

            }
        });
        //  window.showAsDropDown(nextNew, Gravity.BOTTOM, 0, 0);

        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }
    /**
     * 结算订单、支付
     */
    private void lementOnder() {
        //选中的需要提交的商品清单
        for (TrolleyBean bean:shopList){
            boolean choosed = bean.isChoosed();
            if (choosed){
             /*   String shoppingName = bean.getShoppingName();
                int count = bean.getCount();
                double price = bean.getPrice();
                int size = bean.getDressSize();
                String attribute = bean.getAttribute();
                int id = bean.getId();*/
                //Log.e(TAG,id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+size+"--attr---"+attribute);
               // ToastUtil.showL(this,id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+size+"--attr---"+attribute+"==="+totalPrice);
            }
        }
       // ToastUtil.showL(this,"总价："+totalPrice);
        //跳转到支付界面
    }
    /**
     * 单选
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        shopList.get(position).setChoosed(isChecked);
        if (isAllCheck()) {
            ckAll.setChecked(true);

        }else {
            ckAll.setChecked(false);
            shopadapter.notifyDataSetChanged();
            statistics();
        }
    }
    /**
     * 遍历list集合
     * @return
     */
    private boolean isAllCheck() {
        for (TrolleyBean group : shopList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < shopList.size(); i++) {
            TrolleyBean shoppingCartBean = shopList.get(i);
            if (shoppingCartBean.isChoosed()) {
                totalCount++;
                totalPrice += shoppingCartBean.getPrice() * shoppingCartBean.getQuantity();
            }
        }
        java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
        String str = myformat.format(totalPrice);
        trolleyPrice.setText("合计:" + str);
        //tvSettlement.setText("结算(" + totalCount + ")");
    }

    /**
     * 增加
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        TrolleyBean shoppingCartBean = shopList.get(position);
        int currentCount = shoppingCartBean.getQuantity();
        currentCount++;
        shoppingCartBean.setQuantity(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shopadapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 删减
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        TrolleyBean shoppingCartBean = shopList.get(position);
        int currentCount = shoppingCartBean.getQuantity();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        shoppingCartBean.setQuantity(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shopadapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 删除
     *
     * @param position
     */
    @Override
    public void childDelete(int position) {
      //  initFinish();

    }

}
